package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.RepairPassword;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void delete(Long id) {
       employeeMapper.deleteByPrimaryKey(id);
       employeeMapper.deleteByEmployee(id);
    }

    @Override
    public void insert(Employee employee,Long[] ids) {
       employeeMapper.insert(RepairPassword.getPasswordHeightenEmployee(employee));
       if (ids != null){
           for (Long id : ids) {
               employeeMapper.insertRole(employee.getId(),id);
           }
       }

    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee,Long[] ids) {
        employeeMapper.deleteByEmployee(employee.getId());
        if (ids != null){
            for (Long id : ids) {
                employeeMapper.insertRole(employee.getId(),id );
            }
        }
        employeeMapper.updateByPrimaryKey(employee);
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.queryForList(qo);
        return new PageInfo(employees);
    }

    @Override
    public Employee login(String username, String password) {
        if (!StringUtils.hasText(username)){
            throw new LogicException("账号不能为空");
        }
        if (!(StringUtils.hasText(password))){
            throw new LogicException("密码不能为空");
        }
        Employee employee = employeeMapper.login(username, password);
        if (employee == null){
            throw new LogicException("账号或密码不正确");
        }
        if (!employee.isStatus()){
            throw new LogicException("账号已禁用");
        }
        return employee;
    }

    @Override
    public List<String> expression(Long id) {
        return employeeMapper.selectExpression(id);
    }

    @Override
    public void updatePwd(Employee employee) {
        employeeMapper.updatePwd(employee);
    }



    @Override
    public void batchDelete(Long[] ids) {
        if (ids != null && ids.length==0){
            throw new LogicException("最少删除一个");
        }
        employeeMapper.batchDelete(ids);
        employeeMapper.batchDeleteRole(ids);
    }

    @Override
    public HashMap checkName(String name, Long id) {
        HashMap hashMap = new HashMap();
        Employee employee;
        if (id == null){
            employee = employeeMapper.selectCheckName(name);
            if (employee != null){
                hashMap.put("valid", false);
                return hashMap;
            }
            hashMap.put("valid", true);
            return hashMap;
        }else {
            Employee employee1 = employeeMapper.selectByPrimaryKey(id);
            if (employee1.getName().equals(name)){
                hashMap.put("valid", true);
                return hashMap;
            }
            employee = employeeMapper.selectCheckName(name);
            if (employee != null){
                hashMap.put("valid", false);
                return hashMap;
            }
            hashMap.put("valid", true);
            return hashMap;
        }
    }

    @Override
    public void updateStatus(Long id,boolean status) {
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employee.setStatus(!employee.isStatus());
        employeeMapper.updateStatus(employee);
    }

    /**
     * 创建并返回一个excel对象
     *
     */
    @Override
    public Workbook exprotXls() {
        //先创建一个excel对象
        HSSFWorkbook wb = new HSSFWorkbook();

        //设置第一张表和名字
        HSSFSheet sheet = wb.createSheet("用户信息表");

        //设置第一行为标题行
        HSSFRow row = sheet.createRow(0);
        //给标题行每一列赋值
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        //求出数据库的数据
        List<Employee> employees = employeeMapper.selectAll();

        //遍历员工列表,给下面每一行每一列赋值
        for (int i = 0; i <employees.size(); i++){
            row = sheet.createRow(i + 1);
            Employee employee = employees.get(i);
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }


    /**
     * 解析上传的excel文件,并传到数据库中
     */
    @Override
    public void importXls(MultipartFile file) throws Exception {
        //解析上传的文件
        HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());

        //提取第一页
        HSSFSheet sheet = wb.getSheetAt(0);

        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();

        //遍历第一页,从索引1开始读,读到最后一个索引
        for (int i = 1; i<= lastRowNum; i++){
            HSSFRow row = sheet.getRow(i);
            //获取当前行的第一列的数据姓名
            String stringCellValue = row.getCell(0).getStringCellValue();
            //先进行一个判断,因为存在用户乱搞数据的情况,所以只要没有用户名的,就直接停止读取,跳出结束方法
            if (!StringUtils.hasLength(stringCellValue.trim())){
                return;
            }
            //读取第二列的数据
            String stringCellValue1 = row.getCell(1).getStringCellValue();
            double stringCellValue2 = row.getCell(2).getNumericCellValue();
            //把数据封装到一个对象中
            Employee employee = new Employee();
            employee.setName(stringCellValue);
            employee.setEmail(stringCellValue1);
            employee.setAge((int)(stringCellValue2));
            employee.setPassword("1");
            //保存到数据库
            employeeMapper.insert(employee);
        }
    }

    @Override
    public List<Employee> selectByRole(String... name) {
        return employeeMapper.selectByRole(name);
    }
}
